<!DOCTYPE html>
<html>

<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="divport" content="user-scalable=no, width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="renderer" content="webkit">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
	<meta name="format-detection" content="telephone=no">
	<meta name="format-detection" content="email=no" />
	<meta name="screen-orientation" content="portrait">
	<meta name="x5-orientation" content="portrait">
	<meta name="browsermode" content="application">
	<meta name="x5-page-mode" content="app">
	<meta name="full-screen" content="yes">
	<meta name="x5-fullscreen" content="true">
	<meta name="msapplication-tap-highlight" content="no">
	<meta name="description" content="">
	<meta name="keywords" content="">
	<script src="https://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
	<script type="text/javascript" src="jweixin-1.3.2.js"></script>
	<script type="text/javascript" src="md5-1.js" charset="utf-8">
	</script>
	<script type="text/javascript" src="base64.js" charset="utf-8"></script>
	<script>
		sizeWindow();
		window.onresize = sizeWindow;

		function sizeWindow() {
			document.documentElement.style.fontSize = window.innerWidth / 3.75 + 'px';
		}
	</script>
</head>

<body>
	<div id="app" class="container">
		<div class='complaintsCon'>
			<div class='title'>
				上传文件
				<div class='subTitle'>(选填，最大20M) 0M</div>
			</div>
			<div class='uploadCon'>

			</div>
			<div id="uploadButton">

			</div>

		</div>
	</div>
	<script>
		var timmer = null
		var oldId = 0 // 旧文件数组最大id 
		var isImg = (/.jpg$|.png$|.jpeg$|.gif$/i)
		var isMv = (/.flv|.rvmb|.mp4|.avi|.wmv$/i)
		var isDoc = (/.doc$|.xls$|.ppt$|.docx$|.xlsx$|.pptx$|.pdf$/i)
		var isVoice = (/.rm|.mp3|.wma$/i)
		filePath = null
		longInputVal = ''
		sumTxtL = 1000
		textNowL = 0
		classId = 0
		imgSize = 0 //总大小
		imgSumSize = 1024 * 20
		imgArrs = []
		isUpload = false
		var addView =
			" <div bindtap='upload' id='addImg' class='item'><span class='selFile'><input id='uploadInput' type='file'></span</div>"
		var uploadBtn = "<div id='uploadFiles' class='uploadBtn'>上传</div>"
		var uploading = "<div class='uploadBtn' v-else>正在上传中，请稍后....</div>"
		var subTitleView = $('.subTitle')
		$('.uploadCon').append(addView)
		$('#uploadButton').html(uploadBtn)
		// 选择文件
		var input = document.getElementById("uploadInput");
		input.addEventListener('change', selFile, false);
		wx.miniProgram.postMessage({
			data: {
				isNos: false
			}
		})
		checkParams()

		$("#uploadFiles").click(function () {
			uploadFiles()
		})
		$(".uploadCon").off("mouseenter", "#remove").on("mouseenter", "#remove", function () {
			var self = this
			if (this.id === "addImg") {
				return
			}
			var removeId = $(".uploadCon #remove").index(this);
			if (removeId < 0) {
				return
			}
			$(this).parent().remove()
			imgSize = imgSize - imgArrs[removeId].size
			subTitleView.html("(选填，最大20M) " + imgSize.toFixed(4) + "M")

			oldId--
			imgArr = imgArrs.splice(removeId, 1)
		})

		function getQueryString(name) {
			var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
			var r = window.location.search.substr(1).match(reg);
			if (r != null) {
				return decodeURIComponent(r[2]);
			}
			return null;
		}

		function checkParams() {
			// var imgArr = getQueryString('imgArr')
			var imgArr = Base64.decode(getQueryString('imgArr'))
			// var imgArr =
			// 	Base64.decode(
			// 		"W3siaW1nUGF0aCI6Imh0dHBzOi8vZXdtLmx5ZXVrai5jb20vdXBsb2FkL2ZpbGUvMjAxODA5MDQ2MTE3MC5wbmciLCJzaXplIjowLjAwMTg0fV0="
			// 	)


			if (imgArr === '' || !imgArr) {
				return
			}
			var imgArr = JSON.parse(imgArr);
			console.log(imgArr)
			//图片和文件分类
			var relArr = []
			var sumSize = 0
			if (imgArr.length <= 0) {
				alert('上传文件不能为空')
				return
			}
			for (let c = 0; c < imgArr.length; c++) {
				const item = imgArr[c];
				var obj = {}
				if (isImg.test(item.imgPath)) {
					obj.imgPath = item.imgPath
					addImg(obj)
				} else {
					obj.imgPath = '/file.png'
					addFileImg(obj)

				}
				obj.size = item.size
				sumSize += item.size
				relArr.push(obj)
			}
			oldId = imgArr.length
			imgSize = sumSize
			subTitleView.html("(选填，最大20M) " + imgSize.toFixed(4) + "M")
			imgArrs = relArr
		}

		function selFile(e) {
			var file = e.currentTarget.files[0]
			var fileSize = getFileSize(file.size)
			if (!checkFileType(file.name)) {
				//不识别的文件类型
				alert('上传文件只支持 图片、视频、文档')
				return
			}
			if (imgSize + fileSize > imgSumSize) {
				alert('上传文件总大小不得大于 20M')
				return
			} else {
				imgSize += fileSize
				subTitleView.html("(选填，最大20M) " + imgSize.toFixed(4) + "M")
			}
			var fileObj = {
				name: file.name,
				path: '',
				imgPath: '',
				type: file.type,
				size: fileSize
			}
			if (/image\/\w+/.test(file.type)) {
				var reader = new FileReader();
				//将文件以Data URL形式读入页面
				reader.readAsDataURL(file);
				reader.onload = function () {}
				setTimeout(function () {
					fileObj.imgPath = reader.result
					imgArrs.push(fileObj)
					addImg(fileObj)
				}, 100);
			} else {
				var reader = new FileReader();
				//将文件以Data URL形式读入页面
				reader.readAsDataURL(file);
				reader.onload = function () {}
				setTimeout(function () {
					fileObj.path = reader.result
					imgArrs.push(fileObj)
					addFileImg(fileObj)
				}, 100);
			}

		}

		function addFileImg(e) {
			$('#addImg').before("<div id='img' class='item'><img class='img' " + 'src=/file.png' +
				"></img><div id='remove'   class='removeImg'> 删除</div</div>")

		}

		function addImg(e) {
			$('#addImg').before("<div id='img' class='item'><img class='img' " + 'src=' + e.imgPath +
				"></img><div id='remove'  class='removeImg'> 删除</div</div>")
		}
		// 文件大小计算 M
		function getFileSize(limit) {
			var size = (limit / (1024 * 1024)).toFixed(5)
			return Number(size)
		}
		//检查文件类型
		function checkFileType(name) {
			if (isImg.test(name) || isMv.test(name) || isDoc.test(name) || isVoice.test(name)) {
				return true
			} else {
				return false
			}
		}

		function getToken() {

			var date = new Date()
			const year = date.getFullYear()
			const month = date.getMonth() + 1
			const day = date.getDate()
			var arr = [year, month, day]
			var dateStr = ''
			for (let a = 0; a < arr.length; a++) {
				const item = arr[a];
				var n = item.toString()
				dateStr += n[1] ? n : '0' + n
			}

			var API_KEY = 'l2V|gfZp{8`;jzR~6Y1_'
			return md5('402268348' + dateStr + API_KEY)
		}
		// 上传文件
		function uploadFiles() {

			var formData = new FormData()
			var base64DataArr = []
			var fileNameArr = []
			var sizeArr = []
			var access_token = getToken()
			if (imgArrs.length === 0) {
				alert('上传文件不能为空')
				return
			}
			$('#uploadButton').html(uploading)
			var newImg = imgArrs.slice(oldId, imgArr.length)
			var oldImg = imgArrs.slice(0, oldId)
			for (let i = 0; i < newImg.length; i++) {
				const item = newImg[i];
				if (item.path) {
					base64DataArr.push(item.path)
				} else {
					base64DataArr.push(item.imgPath)
				}
				fileNameArr.push(item.name)
				sizeArr.push(item.size)
			}

			formData.append('access_token', access_token)
			formData.append('title', fileNameArr)
			formData.append('size', sizeArr)
			formData.append('file', base64DataArr)

			isUpload = true
			$.ajax({
				url: 'http://172.16.2.105:9001/api/HumanResourcesExcel/PostExcelFiles',
				type: 'POST',
				data: formData,
				//这两个设置项必填
				contentType: false,
				processData: false,
				success: function (data) {
					$('#uploadButton').html(uploadBtn)
					if (data.code === 0) {
						//向微信推送消息
						var oldArr = []
						var resultData = {
							file: '',
							size: ''
						}
						if (oldImg.length > 0) {
							for (let d = 0; d < oldImg.length; d++) {
								const item = oldImg[d];
								var obj = {}
								resultData.file += item.imgPath + ','
								resultData.size += item.size + ','
							}
						}
						resultData.file += data.data.file
						resultData.size += data.data.size

						isUpload = false
						wx.miniProgram.postMessage({
							data: resultData
						})
						wx.miniProgram.navigateBack()
					} else {
						isUpload = false
						alert('网络有问题。。。请稍后再试')
					}
				},
				complete: function () {}
			})

		}
	</script>
	<style>
		.uploadBtn {
			text-align: center;
			font-size: 0.15rem;
			color: #fff;
			background: #103557;
			padding: 0.1rem 0;
			border-radius: 0.1rem;
		}

		input::-webkit-input-placeholder {
			font-size: 0.14rem;
			padding: 0.1rem;
			height: 40px;
			color: #CCCCCC
		}

		input::-webkit-input-placeholder,
		textarea::-webkit-input-placeholder {
			color: #CCCCCC;
		}

		input:-moz-placeholder,
		textarea:-moz-placeholder {
			color: #CCCCCC;
		}

		input::-moz-placeholder,
		textarea::-moz-placeholder {
			color: #CCCCCC;
		}

		input:-ms-input-placeholder,
		textarea:-ms-input-placeholder {
			color: #CCCCCC;
		}

		.selFile {
			position: relative;
			display: inline-block;
			overflow: hidden;
			background: url(/add.jpg) no-repeat top left;
			background-size: 100% 100%;
			width: 1rem;
			height: 1rem;
		}

		.selFile input {
			position: absolute;
			right: 0px;
			top: 0px;
			opacity: 0;
			-ms-filter: 'alpha(opacity=0)';
			font-size: 200px;
		}

		.messageCon {
			display: block;
			width: 100%;
			min-height: 0.32rem;
			line-height: 2.3;
			position: fixed;
			top: 0;
			left: 0;
			right: 0;
			background: #f90;
			color: #fff;
			text-align: center;
			font-size: 0.14rem;
			z-index: 1010;
			opacity: 0;
			-webkit-transform: translateZ(0) translateY(-100%);
			transition: all .4s ease-in-out
		}

		.activeMessage {
			-webkit-transform: translateZ(0) translateY(0);
			opacity: 1
		}

		.container {}

		.complaintsCon {
			padding: 0 0.1rem;
			background: #F7F7F7;
		}

		.title {
			padding: 0.06rem 0;
			font-size: 0.16rem;
			color: #666;
			font-weight: bold;
		}

		.title .subTitle {
			display: inline-block;
			font-size: 0.1rem;
			color: #999999;
			font-weight: normal
		}

		.cellInput {
			padding: 0.04rem 0.02rem;
			background: #fff;
			border-radius: 0.01rem;
			font-size: 0.14rem;
		}

		.cellInput .input {
			width: 100%;
		}

		.cellInput .inputLong {
			width: 100%;
			height: 1.28rem;
			padding: 0 0.04rem;
		}

		.cellTxtLength {
			width: 100%;
			text-align: right;
			color: #ccc;
			font-size: 0.14rem;
		}

		.complaintsClass {
			display: flex;
			width: 100%;
			justify-content: space-around;
			align-items: center;
		}

		.complaintsClass .classItem {
			padding: 0.1rem 0.4rem;
			background: #fff;
			border-radius: 0.1rem;
			font-size: 0.14rem;
		}

		.complaintsClass .activeClassItem {
			background: #00B6E0;
			color: #fff
		}

		.uploadCon {
			display: flex;
			flex-flow: row wrap;
			align-content: flex-start;
			padding-left: 2%;
			padding-right: 2%;
		}

		.uploadCon .item {
			position: relative;
			top: 0;
			padding: 0.1rem 0.1rem;
			width: 33.33333333%;
			box-sizing: border-box;
		}

		.uploadCon .item .removeImg {
			text-align: center;
			font-size: 0.1rem;
			color: #fff;
			background: rgba(0, 0, 0, 0.5);
			position: absolute;
			width: 1rem;
			padding: 0.03rem 0;
			left: 0.1rem;
			bottom: 0.13rem;
		}

		.uploadCon .item .img {
			width: 1rem;
			height: 1rem;
			flex-shrink: 0
		}

		.uploadCon .item .addImg {
			width: 1rem;
			height: 1rem;
			border: 0.01rem dashed red;
			flex-shrink: 0
		}
	</style>

</body>

</html>